﻿using DevExpress.Utils.Win;
using DevExpress.XtraEditors.Popup;
using DevExpress.XtraGrid.Demos.util;
using DevExpress.XtraGrid.Editors;
using DevExpress.XtraLayout;
using DXApplicationTangche.Const;
using DXApplicationTangche.DTO;
using DXApplicationTangche.UC.成品出库单;
using DXApplicationTangche.UC.成品出库单.service;
using DXApplicationTangche.UC.成衣进销存.service;
using DXApplicationTangche.UC.销售记录.service;
using DXApplicationTangche.UC.门店出入库.Service;
using DXApplicationTangche.UC.门店出入库.UC;
using DXApplicationTangche.Utils;
using Seagull.BarTender.Print;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using static DXApplicationTangche.UC.成衣进销存.service.成衣进销存Service;

namespace DXApplicationTangche.UC.标签打印
{
    public partial class Form出入库 : DevExpress.XtraEditors.XtraForm
    {
        //入库
        private List<TagPrintDTO> tagPrintDTOs = new List<TagPrintDTO>();
        private TagPrintDTO tagPrint = new TagPrintDTO();
        //出库
        private List<StockInOutDetailDTO> stockInOutDetailDTOs出库 = new List<StockInOutDetailDTO>();
        private StockInOutDetailDTO stockInOutDetail出库 = new StockInOutDetailDTO();
        //调拨出库
        private List<StockInOutDetailDTO> StockInOutDetailDTOs = new List<StockInOutDetailDTO>();
        private StockInOutDetailDTO stockInOutDetailDTO = new StockInOutDetailDTO();
        private String sessionId;
        private String shopId;
        private String shopName;
        private Enum成衣进销存 enum成衣进销存 = Enum成衣进销存.未知;
        //库存
        private XtraUserControl库存明细 xtraUserControl;
        //出库明细
        private XtraUserControl库存流水 xtraUserControl每日出成品仓和抖音仓的明细;

        public Form出入库()
        {
            InitializeComponent();
            //调拨出库
            this.sessionId = new FunctionHelper().Uuid;
            this.searchLookUpEdit店铺.Properties.DataSource = 销售记录Service.get店铺();
            //库存
            this.xtraUserControl = new XtraUserControl库存明细();
            this.xtraUserControl.Dock = DockStyle.Fill;
            this.panel库存.Controls.Clear();
            this.panel库存.Controls.Add(this.xtraUserControl);
            //出库明细
            List<String> storeId每日成品仓和抖音仓的明细 = new List<String>();
            storeId每日成品仓和抖音仓的明细.Add("5");
            storeId每日成品仓和抖音仓的明细.Add("14");
            //  每日出成品仓和抖音仓的明细
            this.xtraUserControl每日出成品仓和抖音仓的明细 = new XtraUserControl库存流水("出库", storeId每日成品仓和抖音仓的明细);
            this.xtraUserControl每日出成品仓和抖音仓的明细.Dock = DockStyle.Fill;
            this.panel出库明细.Controls.Clear();
            this.panel出库明细.Controls.Add(this.xtraUserControl每日出成品仓和抖音仓的明细);
        }
        private void print质检合格证()
        {
            //获取不同模板
            String filePath质检模板 = "stock_qcpass.btw";
            String fileName质检模板 = Path.GetFileName(filePath质检模板);
            //根据相对路径判断模板是否存在
            //不存在则下载进行打印
            if (!System.IO.File.Exists(@"tag\" + fileName质检模板))
            {
                FileUtil.DownloadPicture(URL.图片url + URL.打印模板路径 + filePath质检模板, @"tag\" + fileName质检模板, -1);
            }
            String str = System.AppDomain.CurrentDomain.BaseDirectory;
            //String str = System.AppDomain.CurrentDomain.BaseDirectory;
            //新建BarTender并启动，模板位置
            Engine btEngine = new Engine();
            btEngine.Start();
            LabelFormatDocument btFormat = btEngine.Documents.Open(str + @"tag\" + fileName质检模板);
            //指定打印机名 
            btFormat.PrintSetup.PrinterName = "TSC TTP-244 Pro";
            //btFormat.PrintSetup.PrinterName = "POSTEK G-3106";
            //打印份数                   
            btFormat.PrintSetup.IdenticalCopiesOfLabel = 1;
            //改变标签打印数份连载 
            btFormat.PrintSetup.NumberOfSerializedLabels = 1;
            //对BTW模版相应字段进行赋值 

            btFormat.SubStrings["styleNameCn"].Value = this.tagPrint.styleNameCn;
            btFormat.SubStrings["materialCode"].Value = this.tagPrint.materialCode;
            btFormat.SubStrings["styleSizeCd"].Value = this.tagPrint.styleSizeCd;
            btFormat.SubStrings["inventoryNo"].Value = this.tagPrint.inventoryNo;
            btFormat.SubStrings["printDate"].Value = DateTime.Now.ToString("yyyy/MM/dd");

            Messages messages;
            int waitout = 10000; // 10秒 超时 
            Seagull.BarTender.Print.Result nResult1 = btFormat.Print("质检合格证" + this.tagPrint.inventoryNo, waitout, out messages);
            btFormat.PrintSetup.Cache.FlushInterval = CacheFlushInterval.PerSession;
            //不保存对打开模板的修改 
            btFormat.Close(SaveOptions.DoNotSaveChanges);
            //结束打印引擎                  
            btEngine.Stop();
        }

        private void textBox水洗_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyValue == 13)
            {
                if (!String.IsNullOrWhiteSpace(this.textBox水洗.Text))
                {
                    try
                    {
                        //  入库
                        this.tagPrint = 出入库Service.garmentWipFactoryStockIn(this.textBox水洗.Text.Trim());
                        try
                        {
                            if (!String.IsNullOrEmpty(this.tagPrint.styleSizeCd))
                            {
                                this.tagPrint.styleSizeCd = this.tagPrint.styleSizeCd.Replace("IGS_GROUP_SIZE-", "").Replace("EGS_GROUP_SIZE-", "");
                            }
                        }
                        catch { }
                        //  打印入库贴
                        //this.print质检合格证();
                        //  gridcontrol显示
                        if (!String.IsNullOrEmpty(this.tagPrint.inventoryNo))
                        {
                            if (this.tagPrintDTOs.Count > 0)
                            {
                                if (!this.tagPrintDTOs.Exists(dto => dto.inventoryNo.Equals(this.tagPrint.inventoryNo)))
                                {
                                    this.tagPrintDTOs.Add(this.tagPrint);
                                }
                            }
                            else
                            {
                                this.tagPrintDTOs.Add(this.tagPrint);
                            }
                        }
                        this.gridControl入库一览.DataSource = this.tagPrintDTOs;
                        this.gridView入库一览.RefreshData();
                        this.gridView入库一览.BestFitColumns();
                        this.textBox水洗.Clear();
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(ex.Message);
                    }
                }
                else
                {
                    MessageBox.Show("请扫码");
                }
            }
        }

        private void simpleButton入库清空_Click(object sender, EventArgs e)
        {
            this.tagPrintDTOs = null;
            this.gridControl入库一览.DataSource = this.tagPrintDTOs;
            this.gridView入库一览.RefreshData();
        }

        private void simpleButton出库清空_Click(object sender, EventArgs e)
        {
            this.stockInOutDetailDTOs出库 = null;
            this.gridControl出库一览.DataSource = this.stockInOutDetailDTOs出库;
            this.gridView出库一览.RefreshData();
        }

        private void textBox出库水洗_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyValue == 13)
            {
                if (!String.IsNullOrWhiteSpace(this.textBox出库水洗.Text))
                {
                    try
                    {
                        //  出库
                        this.stockInOutDetail出库 = 出入库Service.factoryOtherSaleOut(this.textBox出库水洗.Text.Trim());
                        //  尺码清洗
                        try
                        {
                            if (!String.IsNullOrEmpty(this.stockInOutDetail出库.styleSizeCd))
                            {
                                this.stockInOutDetail出库.styleSizeCd = this.stockInOutDetail出库.styleSizeCd.Replace("IGS_GROUP_SIZE-", "").Replace("EGS_GROUP_SIZE-", "");
                            }
                        }
                        catch { }
                        //  打印出库贴
                        //this.print出库合格证();
                        //  gridcontrol显示
                        if (!String.IsNullOrEmpty(this.stockInOutDetail出库.barcode))
                        {
                            if (this.stockInOutDetailDTOs出库.Count > 0)
                            {
                                if (!this.stockInOutDetailDTOs出库.Exists(dto => dto.barcode.Equals(this.stockInOutDetail出库.barcode)))
                                {
                                    this.stockInOutDetailDTOs出库.Add(this.stockInOutDetail出库);
                                }
                            }
                            else
                            {
                                this.stockInOutDetailDTOs出库.Add(this.stockInOutDetail出库);
                            }
                        }
                        this.gridControl出库一览.DataSource = this.stockInOutDetailDTOs出库;
                        this.gridView出库一览.RefreshData();
                        this.gridView出库一览.BestFitColumns();
                        this.textBox出库水洗.Clear();
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(ex.Message);
                    }
                }
                else
                {
                    MessageBox.Show("请扫码");
                }
            }
        }
        private void print出库合格证()
        {
            //获取不同模板
            String filePath质检模板 = "stock_qcpass_out.btw";
            String fileName质检模板 = Path.GetFileName(filePath质检模板);
            //根据相对路径判断模板是否存在
            //不存在则下载进行打印
            if (!System.IO.File.Exists(@"tag\" + fileName质检模板))
            {
                FileUtil.DownloadPicture(URL.图片url + URL.打印模板路径 + filePath质检模板, @"tag\" + fileName质检模板, -1);
            }
            String str = System.AppDomain.CurrentDomain.BaseDirectory;
            //String str = System.AppDomain.CurrentDomain.BaseDirectory;
            //新建BarTender并启动，模板位置
            Engine btEngine = new Engine();
            btEngine.Start();
            LabelFormatDocument btFormat = btEngine.Documents.Open(str + @"tag\" + fileName质检模板);
            //指定打印机名 
            btFormat.PrintSetup.PrinterName = "TSC TTP-244 Pro";
            //btFormat.PrintSetup.PrinterName = "POSTEK G-3106";
            //打印份数                   
            btFormat.PrintSetup.IdenticalCopiesOfLabel = 1;
            //改变标签打印数份连载 
            btFormat.PrintSetup.NumberOfSerializedLabels = 1;
            //对BTW模版相应字段进行赋值 

            btFormat.SubStrings["styleNameCn"].Value = this.stockInOutDetail出库.styleNameCn;
            btFormat.SubStrings["materialCode"].Value = this.stockInOutDetail出库.fabricCode;
            btFormat.SubStrings["styleSizeCd"].Value = this.stockInOutDetail出库.styleSizeCd;
            btFormat.SubStrings["inventoryNo"].Value = this.stockInOutDetail出库.barcode;
            btFormat.SubStrings["printDate"].Value = DateTime.Now.ToString("yyyy/MM/dd");

            Messages messages;
            int waitout = 10000; // 10秒 超时 
            Seagull.BarTender.Print.Result nResult1 = btFormat.Print("出库合格证" + this.stockInOutDetail出库.barcode, waitout, out messages);
            btFormat.PrintSetup.Cache.FlushInterval = CacheFlushInterval.PerSession;
            //不保存对打开模板的修改 
            btFormat.Close(SaveOptions.DoNotSaveChanges);
            //结束打印引擎                  
            btEngine.Stop();
        }
        private Boolean checkOrderType(String barcode)
        {
            Boolean checkIsMTO = 成衣进销存Service.checkIsMTO(barcode);
            if (this.enum成衣进销存.Equals(Enum成衣进销存.未知))
            {
                this.enum成衣进销存 = checkIsMTO ? Enum成衣进销存.MTO库存 : Enum成衣进销存.MTS库存;
                return true;
            }
            else
            {
                if (this.enum成衣进销存.Equals((checkIsMTO ? Enum成衣进销存.MTO库存 : Enum成衣进销存.MTS库存)))
                {
                    return true;
                }
                else
                {
                    return false;
                }
            }
        }
        private void textBox扫描_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyValue == 13)
            {
                if (String.IsNullOrEmpty(this.shopId))
                {
                    MessageBox.Show("请先选择调拨入库店铺");
                    return;
                }
                if (!String.IsNullOrWhiteSpace(this.textBox扫描.Text))
                {
                    try
                    {
                        // 成衣库存类型判断
                        if (this.checkOrderType(this.textBox扫描.Text.Trim()))
                        {
                            //扫描成衣码出库
                            StockOutDetailLimitMessageReslt plainMessageResult =
                                成品出库单Service.preStockInOutDetailWithCustomerInfoByBarcodeLimit(
                                    this.sessionId,
                                    this.textBox扫描.Text.Trim(),
                                    0,
                                    this.enum成衣进销存.Equals(Enum成衣进销存.MTO库存) ? StockInOutTypeConst.MTODelivery : StockInOutTypeConst.FactoryDeliveryOut,
                                    this.enum成衣进销存.Equals(Enum成衣进销存.MTO库存) ? this.shopId : Convert.ToString(Convert.ToInt32(this.shopId) + 10)
                                    );
                            FunctionHelper.JsonSerialization(plainMessageResult.stockInOutDetailDTO);
                            //if (!"200".Equals(plainMessageResult.errorCode))
                            //{
                            //    //  最新出入库记录为出库，不能重复出库
                            //    StockInOutDetailDTO stockInOutDetailDTO = plainMessageResult.stockInOutDetailDTO;
                            //    MessageBox.Show(stockInOutDetailDTO.toString());
                            //    this.textBox扫描.Clear();
                            //    return;
                            //}
                            //else
                            //{
                            //    //this.stockInOutDetailDTO =    //扫描成衣码出库
                            //    //    成品出库单Service.preStockInOutDetailWithCustomerInfoByBarcode(
                            //    //        this.sessionId,
                            //    //        this.textBox扫描.Text.Trim(),
                            //    //        0,
                            //    //        "工厂成衣调拨出库",
                            //    //        this.shopId
                            //    //        );
                            //    //  出库
                            this.stockInOutDetailDTO = plainMessageResult.stockInOutDetailDTO;
                            try { this.stockInOutDetailDTO.styleSizeCd = this.stockInOutDetailDTO.styleSizeCd.Replace("IGS_GROUP_SIZE-", "").Replace("EGS_GROUP_SIZE-", ""); } catch { }
                            this.print出库合格证();
                            if (!String.IsNullOrEmpty(this.stockInOutDetailDTO.barcode))
                            {
                                if (this.StockInOutDetailDTOs.Count > 0)
                                {
                                    if (!this.StockInOutDetailDTOs.Exists(dto => dto.barcode.Equals(this.stockInOutDetailDTO.barcode)))
                                    {
                                        this.StockInOutDetailDTOs.Add(this.stockInOutDetailDTO);
                                    }
                                }
                                else
                                {
                                    this.StockInOutDetailDTOs.Add(this.stockInOutDetailDTO);
                                }
                            }
                            this.gridControl成品出库.DataSource = this.StockInOutDetailDTOs;
                            this.gridView成品出库.RefreshData();
                            this.gridView成品出库.BestFitColumns();
                            //}
                        }
                        else
                        {
                            MessageBox.Show("订单类型与其它几件不同，请另外打印出库单");
                            this.textBox扫描.Clear();
                            return;
                        }
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(ex.Message);
                    }
                    this.textBox扫描.Clear();
                }
                else
                {
                    MessageBox.Show("请扫码");
                }
            }
        }

        private void simpleButton确认_Click(object sender, EventArgs e)
        {
            if (this.StockInOutDetailDTOs.Count > 0)
            {
                String str = FunctionHelper.JsonSerialization(this.StockInOutDetailDTOs);
                new Form成品出库单确认(
                    this.sessionId,
                    this.shopId,
                    this.shopName,
                    this.enum成衣进销存.Equals(Enum成衣进销存.MTO库存) ? StockInOutTypeConst.MTODelivery : StockInOutTypeConst.FactoryDeliveryOut,
                    this.StockInOutDetailDTOs,
                    this.enum成衣进销存
                    ).ShowDialog();
                this.enum成衣进销存 = Enum成衣进销存.未知;
                this.StockInOutDetailDTOs.Clear();
                this.sessionId = new FunctionHelper().Uuid;
                this.gridControl成品出库.DataSource = this.StockInOutDetailDTOs;
                this.gridView成品出库.RefreshData();
                this.gridView成品出库.BestFitColumns();
            }
            else
            {
                MessageBox.Show("无确认数据");
            }
        }

        private void simpleButton清空_Click(object sender, EventArgs e)
        {
            this.StockInOutDetailDTOs = null;
            this.gridControl成品出库.DataSource = this.StockInOutDetailDTOs;
            this.gridView成品出库.RefreshData();
        }

        #region 选择店铺
        private void searchLookUpEdit店铺_Popup(object sender, EventArgs e)
        {
            PopupSearchLookUpEditForm form = (sender as IPopupControl).PopupWindow as PopupSearchLookUpEditForm;
            SearchEditLookUpPopup popup = form.Controls.OfType<SearchEditLookUpPopup>().FirstOrDefault();
            LayoutControl layout = popup.Controls.OfType<LayoutControl>().FirstOrDefault();
            //如果窗体内空间没有确认按钮，则自定义确认simplebutton，取消simplebutton，选中结果label
            if (layout.Controls.OfType<Control>().Where(ct => ct.Name == "btOK").FirstOrDefault() == null)
            {
                //得到空的空间
                EmptySpaceItem a = layout.Items.Where(it => it.TypeName == "EmptySpaceItem").FirstOrDefault() as EmptySpaceItem;

                //得到取消按钮，重写点击事件
                Control clearBtn = layout.Controls.OfType<Control>().Where(ct => ct.Name == "btClear").FirstOrDefault();
                LayoutControlItem clearLCI = (LayoutControlItem)layout.GetItemByControl(clearBtn);
                clearBtn.Click += clear店铺Btn_Click;

                //添加一个simplebutton控件(确认按钮)
                LayoutControlItem myLCI = (LayoutControlItem)clearLCI.Owner.CreateLayoutItem(clearLCI.Parent);
                myLCI.TextVisible = false;
            }
        }
        private void searchLookUpEdit店铺View_Click(object sender, EventArgs e)
        {
            int[] a = this.searchLookUpEdit店铺.Properties.View.GetSelectedRows();
            if (a.Length > 0)
            {
                foreach (int rowHandle in a)
                {
                    this.shopId = this.searchLookUpEdit店铺.Properties.View.GetRowCellValue(rowHandle, "id").ToString();
                    this.shopName = this.searchLookUpEdit店铺.Properties.View.GetRowCellValue(rowHandle, "name").ToString();
                }
            }
        }

        /// <summary>
        /// 清除按钮事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void clear店铺Btn_Click(object sender, EventArgs e)
        {
            this.searchLookUpEdit店铺.ToolTip = null;
            searchLookUpEdit店铺.EditValue = null;
        }
        private void searchLookUpEdit店铺_CustomDisplayText(object sender, DevExpress.XtraEditors.Controls.CustomDisplayTextEventArgs e)
        {
            if (null != e.Value)
                e.DisplayText = this.shopName;
        }
        #endregion

    }
}
